package com.yrd.common.webui;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

@SuppressWarnings("serial")
public class DispatchServlet extends HttpServlet{
	String servletPackage;
	public DispatchServlet(String servletPackage) {
		super();
		this.servletPackage = servletPackage;
	}
	
	ConcurrentHashMap<String, Object> servletMap = new ConcurrentHashMap<String, Object>();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String url = request.getRequestURL().toString();
		String clazzAndMethod = StringUtils.substringAfter(url, "request/");
		clazzAndMethod = StringUtils.substringBefore(clazzAndMethod, "?");
		String[] clazzAndMethodArr = clazzAndMethod.split("/");
		String clazzName = clazzAndMethodArr[0];
		String methodName = clazzAndMethodArr[1];
		String clazzNameFull = servletPackage+"."+clazzName;
		try {
			Object servlet = servletMap.get(clazzNameFull);
			ClassInfo classInfo=null;
			if(servlet==null){
				Class<?> clazz = Class.forName(clazzNameFull);
				classInfo = ClassInfo.find(clazz);
				Method method = classInfo.getMethod(methodName);
				servlet = clazz.newInstance();
				servletMap.put(clazzNameFull, servlet);
				method.invoke(servlet, request,response);
			}else{
				classInfo= ClassInfo.find(servlet.getClass());
				Method method = classInfo.getMethod(methodName);
				method.invoke(servlet, request,response);
			}
		} catch (Exception e) {
			throw new ServletException(e);
		}
		
	}
}
